package com.alogic.swagger.redoc;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsArray;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.doc.json.JsonArray;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;
import java.util.List;

/**
 * Redoc扩展:TagGroup
 *
 * @since 1.6.13.7 [20200812 duanyy] <br>
 */
public class SwaggerTagGroup extends AbstractLogiclet {
    private String $name;
    private String $tags;

    public SwaggerTagGroup(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $name = PropertiesConstants.getRaw(p,"name",$name);
        $tags = PropertiesConstants.getRaw(p,"tags",$tags);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        XsArray newCurrent = current.getArrayChild("x-tagGroups",true);
        XsObject newObj = newCurrent.newObject();
        newObj.addProperty("name",PropertiesConstants.transform(ctx,$name,""));
        String [] tags = PropertiesConstants.transform(ctx,$tags,"").split(",");
        if (tags.length > 0){
            XsArray array = newObj.getArrayChild("tags",true);
            if (array instanceof JsonArray){
                JsonArray jsonArray = (JsonArray)array;
                @SuppressWarnings("unchecked")
                List<Object> content = (List<Object>)jsonArray.getContent();
                for (String tag:tags){
                    if (StringUtils.isNotEmpty(tag)){
                        content.add(tag);
                    }
                }
            }
        }
        newCurrent.add(newObj);
    }
}